﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Diagnostics;
using System.Xml;
using System.IO;
using System.Configuration;

namespace TJ_MainNameSpace
{
    public partial class FormStart : Form
    {
        public FormStart()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
        }
        public static string Wenjian = "";
        public static string Gongcheng_Name = "";
        //public static bool denglu = false;

        MySqlConnection con = new MySqlConnection(global::TongJi_EMS.Properties.Settings.Default.monitorConnection);

        private void RetrievePro()
        {
            string cmdText = @"select pr_name,pr_description,pr_path,pr_time from project";
            try
            {
                con.Open();
                MySqlCommand cmd = new MySqlCommand(cmdText, con);
                MySqlDataAdapter mda = new MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                mda.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
                //dataGridView1.DataBindings.Add("DataSource", ds, ds.Tables[0].TableName);与上面代码作用相同

            }
            catch (Exception e1)
            {
                MessageBox.Show("数据库连接失败", e1.Message);
                //return;
            }
            finally
            {
                con.Close();
            }
        }

        private bool RetrievePro(ref DataSet ds)
        {
            string cmdText = @"select pr_name,pr_description,pr_path,pr_time from project";
            try
            {
                con.Open();
                MySqlCommand cmd = new MySqlCommand(cmdText, con);
                MySqlDataAdapter mda = new MySqlDataAdapter(cmd);
                ds = new DataSet();
                mda.Fill(ds);
                //dataGridView1.DataSource = ds.Tables[0];
                //dataGridView1.DataBindings.Add("DataSource", ds, ds.Tables[0].TableName);与上面代码作用相同
                return true;

            }
            catch (Exception e1)
            {
                MessageBox.Show("数据库连接失败，请配置数据库连接。", e1.Message);
                return false;
                //return;
            }
            finally
            {
                con.Close();
            }
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            Wenjian = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
            Gongcheng_Name = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
        }

        #region 左边按钮事件

        //新建工程
        private void CreateNewPro_Click(object sender, EventArgs e)
        {
            FormNewProj a = new FormNewProj();
            if (a.ShowDialog() == DialogResult.OK)
            {
                RetrievePro();
                EventLog.WriteEntry("TJ_EMS_EventLog", "新建了工程" + a.pr_name, EventLogEntryType.Information);
            }
        }

        //修改工程
        private void ModifyPro_Click(object sender, EventArgs e)
        {
            FormNewProj NP = new FormNewProj(this.dataGridView1.CurrentRow.Cells[0].Value.ToString(),
                                        this.dataGridView1.CurrentRow.Cells[2].Value.ToString(),
                                        this.dataGridView1.CurrentRow.Cells[1].Value.ToString());
            if (NP.ShowDialog() == DialogResult.OK)
            {
                EventLog.WriteEntry("TJ_EMS_EventLog", "工程" + this.dataGridView1.CurrentRow.Cells[0].Value.ToString() + "已被修改", EventLogEntryType.Information);
                RetrievePro();
            }
        }

        //删除工程
        private void DeletePro_Click(object sender, EventArgs e)
        {
            try
            {
                string deletename = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
                if (deletename == null)
                {
                    MessageBox.Show("请选择目前存在的工程！");
                    return;
                }
                if (MessageBox.Show("确定要删除此工程吗？所有与此工程关联的数据均将丢失！",
                              "警告",
                              MessageBoxButtons.OKCancel,
                              MessageBoxIcon.Exclamation) == DialogResult.OK)
                {
                    con.Open();
                    string cmdText = @"delete from project where pr_name='" + deletename + "'";
                    MySqlCommand cmd = new MySqlCommand(cmdText, con);
                    cmd.ExecuteNonQuery();
                    EventLog.WriteEntry("TJ_EMS_EventLog", "工程" + deletename + "已被删除！", EventLogEntryType.Warning);
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
            finally
            {
                con.Close();
                RetrievePro();
            }

        }

        //打开当前工程
        private void OpenPro_Click(object sender, EventArgs e)
        {
            TongJi_EMS._Management.ProjectManager.Instance.CurProjectPath = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
            Gongcheng_Name = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
            TongJi_EMS._Management.ProjectManager.Instance.CurProjectName = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
            try
            {
                string fileName = null;

                // Open File Dialog
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.DefaultExt = "pro";
                dlg.Filter = "组态工程文件|*.pro";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (!dlg.FileName.EndsWith("pro"))
                    {
                        MessageBox.Show("请选择正确的文件格式", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    fileName = dlg.FileName;
                }

                if (fileName == null)
                    return;
                RunningForm l_runF = new RunningForm(fileName);
                this.Hide();
                l_runF.Owner = this;
                l_runF.Show();
            }
            catch
            {
                MessageBox.Show("打开工程文件错误");
            }
        }

        //进入组态开发
        private void EnterDevelop_Click(object sender, EventArgs e)
        {
            Wenjian = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
            TongJi_EMS._Management.ProjectManager.Instance.CurProjectPath = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
            Gongcheng_Name = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
            TongJi_EMS._Management.ProjectManager.Instance.CurProjectName = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
            string[] MyFiles = null;
            if (Wenjian.Length > 0)
            {
                //Form2 a = new Form2();
                //a.Show();
                //EventLog.WriteEntry("TJ_EMS_EventLog", "进入新的组态画面", EventLogEntryType.Information);
                try
                {
                    MyFiles = System.IO.Directory.GetFiles(Wenjian);
                }
                catch (Exception)
                {
                    MessageBox.Show("找不到项目路径，请手动指定项目文件夹！");
                }
                if (MyFiles == null || MyFiles.Length == 0)
                {
                    this.Hide();
                    MainDesignForm a = new MainDesignForm();
                    a.Owner = this;
                    a.Show();
                    EventLog.WriteEntry("TJ_EMS_EventLog", "进入新的组态画面", EventLogEntryType.Information);
                    a.Focus();
                }

                else
                {
                    this.Hide();
                    //openFileDialog1.InitialDirectory = FormStart.Wenjian;
                    MainDesignForm a = new MainDesignForm();
                    a.Owner = this;
                    a.Show();
                    EventLog.WriteEntry("TJ_EMS_EventLog", "进入工程(" + Gongcheng_Name + ")组态界面", EventLogEntryType.Information);
                    //openFileDialog1.Filter = "DAT File|*.dat";
                    //openFileDialog1.Title = "Select a DAT File";
                    //if (MyFiles.Length == 1)
                    //{ a.Deserialize(MyFiles[0]); }
                    //else if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    //{

                    //    string fimename1 = openFileDialog1.FileName;
                    //    a.Deserialize(fimename1);
                    //}
                    a.Focus();
                }
            }
            else { MessageBox.Show("请先选择一个项目"); }
        }

        //退出系统
        private void Exit_Click(object sender, EventArgs e)
        {
            EventLog.WriteEntry("TJ_EMS_EventLog", "系统已退出！", EventLogEntryType.Warning);
            this.Close();
        }

        #endregion

        #region "系统"下拉菜单点击事件

        private void userLogonToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormLogon a = new FormLogon();
            if (a.ShowDialog() == DialogResult.OK)
            {
                //denglu = true;
                Reload_FormStart();
            }
        }

        private void userLogoffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("此操作将切换用户,务须退出此系统");
            //MainForm.quanxian = false;
            EventLog.WriteEntry("TJ_EMS_EventLog", "用户'" + FormLogon.Yonghu_Name + "'已注销", EventLogEntryType.Warning);
            //Form3 a = new Form3();
            //a.Show();
            this.userLogonToolStripMenuItem.Enabled = true;
            this.userLogoffToolStripMenuItem.Enabled = false;
            //denglu = false;
            TongJi_EMS._Management.UserManager.Instance.LogOff();
            Reload_FormStart();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EventLog.WriteEntry("TJ_EMS_EventLog", "系统已退出！", EventLogEntryType.Warning);
            this.Close();
        }

        #endregion

        #region "文件"下拉菜单点击事件

        private void CreateNewProToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateNewPro_Click(sender, e);

        }

        private void ModifyProToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ModifyPro_Click(sender, e);
        }

        private void DeleteProToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeletePro_Click(sender, e);
        }

        private void OpenProToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenPro_Click(sender, e);
        }

        private void EnterDevelopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EnterDevelop_Click(sender, e);
        }

        #endregion

        #region "数据源"下拉菜单点击事件

        private void dataSourceConfigToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormSourceConfig SC = new FormSourceConfig();
            if (SC.ShowDialog() == DialogResult.OK)
            {
                con = new MySqlConnection(global::TongJi_EMS.Properties.Settings.Default.monitorConnection);
                Reload_FormStart();
            }
        }

        #endregion

        private void FormStart_Load(object sender, EventArgs e)
        {
            if (!EventLog.SourceExists("TJ_EMS_EventLog", "."))
                EventLog.CreateEventSource(new EventSourceCreationData("TJ_EMS_EventLog", "Application"));
            //Check if need autologon
            if (global::TongJi_EMS.Properties.Settings.Default.autologon)
                TongJi_EMS._Management.UserManager.Instance.LogOn(global::TongJi_EMS.Properties.Settings.Default.lastuserid,
                    global::TongJi_EMS.Properties.Settings.Default.lastusername,
                    global::TongJi_EMS.Properties.Settings.Default.lastuserprivilege);
            Reload_FormStart();
        }

        private void Reload_FormStart()
        {
            DataSet ds = new DataSet();
            if (RetrievePro(ref ds))
            {
                this.dataGridView1.DataSource = ds.Tables[0];
                SetButtonEnablity(TongJi_EMS._Management.UserManager.Instance.UserLogon);
                //MainForm.quanxian = true;
            }
            else
            {
                FormSourceConfig SC = new FormSourceConfig();
                if (SC.ShowDialog() == DialogResult.OK)
                {
                    con = new MySqlConnection(global::TongJi_EMS.Properties.Settings.Default.monitorConnection);
                    Reload_FormStart();
                }
            }
        }

        //根据用户权限切换按钮状态
        private void SetButtonEnablity(bool p_denglu)
        {
            this.btn_ModifyPro.Enabled = false;
            this.btn_CreateNewPro.Enabled = false;
            this.btn_DeletePro.Enabled = false;
            this.btn_EnterDevelop.Enabled = false;
            this.btn_OpenPro.Enabled = false;
            this.createNewProToolStripMenuItem.Enabled = false;
            this.modifyProToolStripMenuItem.Enabled = false;
            this.deleteProToolStripMenuItem.Enabled = false;
            this.openProToolStripMenuItem.Enabled = false;
            this.enterDevelopToolStripMenuItem.Enabled = false;
            if (p_denglu)
            {
                this.openProToolStripMenuItem.Enabled = true;
                this.btn_OpenPro.Enabled = true;
                this.userLogonToolStripMenuItem.Enabled = false;
                this.userLogoffToolStripMenuItem.Enabled = true;
                switch (TongJi_EMS._Management.UserManager.Instance.CurUserPrivilege)
                {
                    case TongJi_EMS._Management.UserPrivilege.Guest:
                        break;
                    case TongJi_EMS._Management.UserPrivilege.Operator:
                        break;
                    case TongJi_EMS._Management.UserPrivilege.SeniorOperator:
                    case TongJi_EMS._Management.UserPrivilege.Admin:
                        this.createNewProToolStripMenuItem.Enabled = true;
                        this.modifyProToolStripMenuItem.Enabled = true;
                        this.deleteProToolStripMenuItem.Enabled = true;
                        this.enterDevelopToolStripMenuItem.Enabled = true;
                        this.btn_ModifyPro.Enabled = true;
                        this.btn_CreateNewPro.Enabled = true;
                        this.btn_DeletePro.Enabled = true;
                        this.btn_EnterDevelop.Enabled = true;
                        break;
                    default:
                        break;
                }
            }
            else
            {
                this.openProToolStripMenuItem.Enabled = true;
                this.btn_OpenPro.Enabled = true;
                this.userLogonToolStripMenuItem.Enabled = true;
                this.userLogoffToolStripMenuItem.Enabled = false;
            }
        }
    }
}